package com.example.edu.Service.Impl;

import com.example.edu.Dto.ChapterListDtoG;
import com.example.edu.Dto.ListDtoR;
import com.example.edu.Dto.Return;
import com.example.edu.Entity.Chapter;
import com.example.edu.Entity.User;
import com.example.edu.Mapper.ChapterMapper;
import com.example.edu.Mapper.UserMapper;
import com.example.edu.Service.ChapterService;
import com.example.edu.Utils.CacheDataBaseUtil;
import com.example.edu.Utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.edu.Utils.MyConstants.USER_CACHE_TTL;
import static com.example.edu.Utils.MyConstants.USER_KEY;

@Service
public class ChapterServiceImpl implements ChapterService {
    @Resource
    ChapterMapper chapterMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    CacheDataBaseUtil cacheDataBaseUtil;
    @Resource
    MindMapServiceImpl mindMapService;
    @Resource
    DocumentServiceImpl documentService;
    private static final Logger logger = LoggerFactory.getLogger(ChapterServiceImpl.class);

    @Override
    @Transactional
    public Return create(Chapter chapter) {
        try {
            return create1(chapter);
        } catch (Exception e){
            return Return.fail(1,"创建失败");
        }
    }

    @Override
    public Return getList(HttpServletRequest httpServletRequest,ChapterListDtoG chapterListData) {
        String token = JwtUtil.getTokenFromCookie(httpServletRequest);
        String telephone = JwtUtil.getUsername(token);
        User user = cacheDataBaseUtil.selectById(USER_KEY,telephone, User.class, telephone2->userMapper.getUser(telephone2),
                USER_CACHE_TTL, TimeUnit.HOURS);
        int start = chapterListData.getStart_index();
        int count = chapterListData.getCount();
        int course_id = chapterListData.getCourse_id();
        int total = chapterMapper.getChapterNum(course_id);
        if(user.getRole() == 0)
            return returnTeacherList(start,count,course_id,total,user.getUser_id());
        return returnStudentList(start,count,course_id,total);
    }

    @Override
    @Transactional
    public Return delete(Chapter chapterId) {
        try {
            return delete1(chapterId.getChapter_id());
        } catch (Exception e){
            return Return.fail(1,"删除失败");
        }
    }

    @Override
    @Transactional
    public Return update(Chapter chapter) {
        try {
            return update1(chapter);
        } catch (Exception e){
            return Return.fail(1,"修改失败");
        }
    }

    @Override
    public Return get(Chapter chapter) {
        try {
            int chapter_id = chapter.getChapter_id();
            if (chapter_id == -1)
                return Return.ok(new Chapter("教师专区"));
            if (chapter_id == 0)
                return Return.ok(new Chapter("公共内容"));
            return Return.ok(chapterMapper.getChapter(chapter_id));
        } catch (Exception e){
            logger.error(e.getMessage());
            return Return.fail(1,"获取失败");
        }
    }

    @Transactional
    public Return create1(Chapter chapter) {
        try{
            chapterMapper.addChapter(chapter);
            return Return.ok();
        } catch (Exception e){
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Transactional
    public Return delete1(Integer chapterId) {
        if (chapterId == -1)
            return Return.fail(1,"教师专区不可删除");
        if (chapterId == 0)
            return Return.fail(1,"公共内容不可删除");
        try {
            chapterMapper.deleteChapter(chapterId);
            return Return.ok();
        } catch (Exception e){
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Transactional
    public Return update1(Chapter chapter){
        if (chapter.getChapter_id() == -1)
            return Return.fail(1,"教师专区不可修改");
        if (chapter.getChapter_id() == 0)
            return Return.fail(1,"公共内容不可修改");
        try {
            chapterMapper.updateChapter(chapter);
            return Return.ok();
        } catch (Exception e){
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private Return returnTeacherList(int start, int count, int course_id, int total, int userId){
        mindMapService.autoCreate(userId,course_id);
        documentService.autoCreateOutline(userId,course_id);
        documentService.autoCreatePlan(userId,course_id);
        if (start == 0) {
            List<Chapter> chapters = chapterMapper.getChapters(course_id, start, Math.min(count - 2, total));
            chapters.add(0, new Chapter(-1, "教师专区"));
            chapters.add(1, new Chapter(0, "公共内容"));
            return Return.ok(new ListDtoR(total + 2, chapters));
        }
        if (start == 1) {
            List<Chapter> chapters = chapterMapper.getChapters(course_id, 0, Math.min(count - 1, total));
            chapters.add(0, new Chapter(0, "公共内容"));
            return Return.ok(new ListDtoR(total + 2, chapters));
        }
        List<Chapter> chapters = chapterMapper.getChapters(course_id, start - 2, Math.min(count, total - start + 2));
        if (chapters.isEmpty())
            return Return.ok("这一页还没有章节", new ListDtoR(total + 2, chapters));
        return Return.ok(new ListDtoR(total + 2, chapters));
    }

    private Return returnStudentList(int start,int count,int course_id,int total){
        if (start == 0) {
            List<Chapter> chapters = chapterMapper.getChapters(course_id, start, Math.min(count - 1, total));
            chapters.add(0, new Chapter(0, "公共内容"));
            return Return.ok(new ListDtoR(total + 1, chapters));
        }
        List<Chapter> chapters = chapterMapper.getChapters(course_id, start - 1, Math.min(count, total - start + 1));
        if (chapters.isEmpty())
            return Return.ok("这一页还没有章节", new ListDtoR(total + 1, chapters));
        return Return.ok(new ListDtoR(total + 1, chapters));
    }


}
